package com.oceansoft.mobile.econsole.modules.api.v2.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.oceansoft.mobile.econsole.common.constant.Constant;
import com.oceansoft.mobile.econsole.common.util.HttpClientUtil;
import com.oceansoft.mobile.econsole.modules.api.v2.service.IProjectService;
import com.oceansoft.mobile.econsole.modules.api.v2.service.IProjectYyService;
import com.oceansoft.mobile.econsole.modules.ascproject.entity.ArrangementInfo;
import com.oceansoft.mobile.econsole.modules.ascproject.entity.ProjectInfo;
import com.oceansoft.mobile.econsole.modules.ascproject.entity.ProjectMaterialEntity;
import com.oceansoft.mobile.econsole.modules.ascproject.entity.YyProjectEntity;
import com.oceansoft.mobile.econsole.modules.base.controller.BaseController;
import com.oceansoft.mobile.econsole.modules.base.entity.ApiPager;
import com.oceansoft.mobile.econsole.modules.base.entity.Pager;
import com.oceansoft.mobile.econsole.modules.base.entity.Query;
import com.oceansoft.mobile.econsole.modules.base.entity.Result;
import com.oceansoft.mobile.econsole.modules.member.service.IMemberService;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * Created by wzy on 2016/2/1.
 * 事项预约等
 */
@RestController
@RequestMapping("api/project")
public class ApiProjectController extends BaseController {

    @Resource
    private IMemberService memberService;
    @Resource
    IProjectService projectService;
    @Resource
    IProjectYyService projectYyService;

    /**
     * 获取可预约时间段
     *
     * @param prjGuid 事项，部门等信息
     * @return 可预约时间段列表
     */
    @RequestMapping(value = "yyinfo/{prjGuid}", method = GET)
    public Result getYyPrjInfo(@PathVariable("prjGuid") String prjGuid) {

        YyProjectEntity result = projectYyService.getYyPrjInfo(prjGuid);
        if (result != null) {
            return new Result(Result.SUCC, result);
        }
        return new Result(Result.FAILURE, "暂无数据!");
    }


    /**
     * 获取可预约时间段
     *
     * @param obj 事项，部门等信息
     * @return 可预约时间段列表
     */
    @RequestMapping(value = "yylist", method = POST)
    public Result getYylist(@RequestBody Query obj) {

        Pager<ProjectInfo> result = projectYyService.getPrjYylist(obj);
        if (result.getTotal() > 0) {
            return new Result(Result.SUCC, result);
        }
        return new Result(Result.FAILURE, "暂无数据!");
    }

    /**
     * 获取可预约时间段
     *
     * @param obj 事项，部门等信息
     * @return 可预约时间段列表
     */
    @RequestMapping(value = "arrangement", method = POST)
    public Result getArrangementTime(@RequestBody JSONObject obj) {
        String startTime = obj.getString("startTime");
        String endTime = obj.getString("endTime");
        String caseGuid = obj.getString("caseGuid");
        String orgId = obj.getString("orgId");
        if (startTime.isEmpty() || endTime.isEmpty() || caseGuid.isEmpty() || orgId.isEmpty()) {
            return new Result(Result.FAILURE, "参数不完整!");
        }
        List<ArrangementInfo> result = projectYyService.getArrangeMenet(orgId, caseGuid, startTime, endTime);

        if (result != null) {
            return new Result(Result.SUCC, result);
        }

        return new Result(Result.FAILURE, "暂无数据!");

    }

    /**
     * 提交预约
     *
     * @return 返回操作情况
     */
    @RequestMapping(value = "doarrangement", method = POST)
    public Result doArrange(MultipartHttpServletRequest request) {
        String userGuid = request.getParameter("userGuid");
        String caseNo = request.getParameter("caseNo");//修改，传警种出入境传1，户政传8
        String yyTime = request.getParameter("yyTime");
        String addr = request.getParameter("addr");
        String orgId = request.getParameter("orgid");
        String yySpan = request.getParameter("checkbox");

        List<MultipartFile> files = request.getFiles("fileName");

        String fileStr = "";
        for (int i = 0; i < files.size(); i++) {
            MultipartFile file = files.get(i);
            if (file.getSize() > 0) {
                try {
                    fileStr += file.getOriginalFilename() + "|" + file.getSize() + "|" + request.getParameter("guid" + i) + "|"
                            + request.getParameter("sort" + i) + "|" + request.getParameter("must" + i) + "|"
                            + request.getParameter("material" + i) + "|" + new BASE64Encoder().encode(file.getBytes());
                    fileStr += "~";
                } catch (IOException e) {
                    e.printStackTrace();
                    return new Result(Result.FAILURE, "图片上传失败");
                }
            }
        }

        String pt = request.getParameter("pt");
        Map<String, String> map = (Map<String, String>) request.getSession().getServletContext().getAttribute(Constant.DICT_SYS_PARAMATER);
        String ip = map.get("interfaceip");

        // 实名认证
        String rzResult = memberService.isConfirm(userGuid);
        if (!"1".equals(rzResult)) {
            return new Result(Result.FAILURE, "您的账号未通过实名认证，请至[个人中心]进行实名认证。");
        } else {
            Result result = projectYyService.doArrange(caseNo, userGuid, orgId, yyTime, yySpan, addr, ip, pt);
            if (result.isSucc()) {
                if (!"".equals(result.getData())) {
                    // 上传附件
                    ArrayList<JSONObject> arrayList = new ArrayList<JSONObject>();
                    if (!"".equals(fileStr)) {
                        try {
                            arrayList = uploadFj(fileStr, result.getData().toString());
                        } catch (Exception e) {
                            e.printStackTrace();
                            return new Result(Result.FAILURE, "图片上传失败");
                        }
                    }

                    if (arrayList.size() > 0) {
                        // 办件材料表插入记录
                        insertProjectMaterial(arrayList, (String) result.getData());
                    }
                }
                return new Result(Result.SUCC, "预约成功!");
            } else {
                return new Result(Result.FAILURE, "预约失败!");
            }

        }

    }

    private ArrayList<JSONObject> uploadFj(String fj, String prjguid) throws Exception {
        // 上传的附件
        //String fj = obj.getString("file");
        ArrayList<JSONObject> arrayList = new ArrayList<JSONObject>();
        String[] fjArr = fj.split("~");
        String url = Constant.ProjectUploadIP + "/WebApi/Product/SaveProjectMat";
        //String url = "http://gafw.jl.gov.cn/WebApi/Product/SaveProjectMat";
        for (String fjxx : fjArr) {
            String[] fjDetail = fjxx.split("\\|");
            JSONObject json = new JSONObject();
            // 文件名
            json.put("fileName", fjDetail[0]);
            // 文件扩展名
            json.put("fileExtension", fjDetail[0].substring(fjDetail[0].lastIndexOf("."), fjDetail[0].length()));
            // 文件大小
            json.put("fileSize", fjDetail[1]);
            // 文件内容
            json.put("fileData", fjDetail[6].substring(fjDetail[6].lastIndexOf(",") + 1));
            // 事项材料ID
            json.put("caseMatGuid", fjDetail[2]);
            // 办件表 guid
            json.put("prjguid", prjguid);
            // String result = HttpClientUtil.post(url,json);
            HashMap<String, String> param = new HashMap<String, String>();

            param.put("mat", json.toString());

            String result = HttpClientUtil.doPost(url, param, null);

            JSONObject jsonObject = JSONObject.parseObject(result);
            // 排序
            json.put("sort", fjDetail[3]);
            // 是否必需
            json.put("must", fjDetail[4]);
            // 材料名称
            json.put("material", fjDetail[5]);
            // 事项材料GUID
            json.put("caseMatGuid", ((JSONObject) jsonObject.get("data")).get("caseMatGuid"));
            // 申报材料GUID
            json.put("prjMatGuid", ((JSONObject) jsonObject.get("data")).get("prjMatGuid"));
            arrayList.add(json);
        }
        return arrayList;
    }


    private void insertProjectMaterial(ArrayList<JSONObject> arrayList, String prjGuid) {
        if (arrayList != null && arrayList.size() > 0) {
            for (JSONObject jsonObject : arrayList) {
                /*String caseMatGuid = (String)((JSONObject)jsonObject.get("data")).get("caseMatGuid");
                String prjMatGuid = (String)((JSONObject)jsonObject.get("data")).get("prjMatGuid");*/
                ProjectMaterialEntity projectMaterialEntity = new ProjectMaterialEntity();
                projectMaterialEntity.setLguid((String) jsonObject.get("prjMatGuid"));
                // 办件guid
                projectMaterialEntity.setProjectguid(prjGuid);
                // 材料名称
                projectMaterialEntity.setProjectmaterialname((String) jsonObject.get("material"));
                // 是否必需
                projectMaterialEntity.setIsneed(new BigDecimal((String) jsonObject.get("must")));
                // 提供方式 0:附件
                projectMaterialEntity.setGetmethod("0");
                // 事项材料guid
                projectMaterialEntity.setMaterialguid((String) jsonObject.get("caseMatGuid"));
                // 是否排序
                projectMaterialEntity.setSortid(new BigDecimal((String) jsonObject.get("sort")));
                // 是否归类
                projectMaterialEntity.setIsclass(new BigDecimal(0));
                projectYyService.insertProjectMaterial(projectMaterialEntity);
            }
        }
    }

    @RequestMapping(value = "getyydataarrange", method = GET)
    public Result getYyDataArrange() {
        List<String> result = projectYyService.getYyDataArrange("7");
        return new Result(Result.SUCC, result);
    }


    /**
     * 监管预约
     *
     * @param obj 预约参数
     * @return 返回操作情况
     */
    @RequestMapping(value = "doarrangementJg", method = POST)
    public Result doArrangeJg(@RequestBody JSONObject obj, HttpServletRequest request) {

        String userGuid = obj.getString("userGuid");
        String tableName = obj.getString("tableName");
        String orgId = obj.getString("orgId");
        String caseNo = obj.getString("caseNo");
        String appType = obj.getString("appType");
        String pt = obj.getString("pt");
        //String persionXh = obj.getString("persionXh");

        obj.remove("pt");

        HashMap<String, Object> data = new HashMap<String, Object>();
        Set<String> keys = obj.keySet();
        Iterator<String> it = keys.iterator();
        // 遍历jsonObject数据，添加到Map对象
        while (it.hasNext()) {

            String key = String.valueOf(it.next());

            if (key.equals("tableName"))
                continue;
            if (key.equals("userGuid"))
                continue;
            if (key.equals("orgId"))
                continue;
            if (key.equals("caseNo"))
                continue;
            if (key.equals("appType"))
                continue;


            String value = (String) obj.get(key);
            data.put(key, value);
        }


        Map<String, String> map = (Map<String, String>) request.getSession().getServletContext().getAttribute(Constant.DICT_SYS_PARAMATER);
        String ip = map.get("interfaceip");

        Result result = projectYyService.doArrangeJg(caseNo, userGuid, orgId, tableName, appType, data, ip, pt);
        return result;
    }

    /**
     * 撤销办件
     *
     * @param prjBillId 办件编号
     * @return 返回结果
     */
    @RequestMapping(value = "undo/{prjBillId}", method = GET)
    public Result unDoPrj(@PathVariable("prjBillId") String prjBillId) {
        Result result = projectService.unDoPrj(prjBillId);


        return result;
    }

    /**
     * 办件详细信息
     *
     * @param prjBillId 办件编号
     * @return 办件详细信息
     */
    @RequestMapping(value = "info/{prjBillId}", method = GET)
    public Result getPrjYs(@PathVariable("prjBillId") String prjBillId) {
        String res="";
  try {
              res= HttpClientUtil.doGet(configInfo.getServiceInterfaceAddress()+"/tasks/tsk/"+prjBillId);
//      res= HttpClientUtil.doGet("http://localhost:8084/tasks/tsk/"+prjBillId);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject object= JSON.parseObject(res);
        JSONObject obj= JSON.parseObject(object.getString("data"));
        if(null!=object.getString("data")){
            return new Result(Result.SUCC, obj);

        }

//        ProjectInfo result = projectService.getPrjInfo(prjBillId);
//        if (result != null) {
//            return new Result(Result.SUCC, result);
//        }
        return new Result(Result.FAILURE, "暂无数据!");
    }


    /**
     * 获取预审办件列表
     *
     * @param query 查询参数
     * @return 列表
     */
    @RequestMapping(value = "ys", method = POST)
    public Result getPrjYs(@RequestBody Query query) {

        query.setNumPerPage(Constant.API_PAGE_SIZE);
        Pager<ProjectInfo> result = projectService.getPrjYs(query);
        if (result.getTotal() > 0) {
            return new Result(Result.SUCC, result);
        }
        return new Result(Result.FAILURE, "暂无数据!");
    }


    /**
     * 获取预审办件列表(我的预约)
     *
     * @param query 查询参数
     * @return 列表
     */
    @RequestMapping(value = "myOrder", method = POST)
    public Result getMyOrder(@RequestBody Query query) {
        return projectService.queryMyOrders(query);
    }

    @RequestMapping(value = "bjnew", method = POST)
    public Result getBjNew(@RequestBody Query query) {
//1:已提交 待预审   13：已退回  9：已办结 3：审批中 2：已预审 -1：已撤销
//        query.setNumPerPage(Constant.API_PAGE_SIZE);
//        Pager<ProjectInfo> result = projectService.getBjNew(query);

        String res="";
        try {
            res= HttpClientUtil.doGet(configInfo.getServiceInterfaceAddress()+"/tasks/page?pi="+query.getPageNum()+"&ps=10&q_creator_s_eq="+ query.getLoginId()+"&q_projectstatus_n_in="+query.getProjectstatus());
//             res= HttpClientUtil.doGet("http://localhost:8084/tasks/page?pi="+query.getPageNum()+"&ps=10&q_creator_s_eq="+"3b173956-4a64-4b6b-bfdc-b3cc329fff13&q_projectstatus_n_in="+query.getProjectstatus());
             JSONObject object= JSON.parseObject(res);
            ApiPager apiPager=JSONObject.parseObject(object.getString("data"),ApiPager.class);
            if (apiPager.getTotalPage() > 0) {
                return new Result(Result.SUCC, apiPager);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


        return new Result(Result.FAILURE, "暂无数据!");
    }


    /**
     * 返回办理中列表
     *
     * @param query 查询参数
     * @return 列表
     */
    @RequestMapping(value = "blz", method = POST)
    public Result getPrjBlz(@RequestBody Query query) {

        query.setNumPerPage(Constant.API_PAGE_SIZE);
        Pager<ProjectInfo> result = projectService.getPrjBlz(query);
        if (result.getTotal() > 0) {
            return new Result(Result.SUCC, result);
        }
        return new Result(Result.FAILURE, "暂无数据!");
    }


    /**
     * 返回已办结列表
     *
     * @param query 查询参数
     * @return 列表
     */
    @RequestMapping(value = "ybj", method = POST)
    public Result getPrjYbj(@RequestBody Query query) {

        query.setNumPerPage(Constant.API_PAGE_SIZE);
        Pager<ProjectInfo> result = projectService.getPrjYbj(query);
        if (result.getTotal() > 0) {
            return new Result(Result.SUCC, result);
        }
        return new Result(Result.FAILURE, "暂无数据!");
    }

    /**
     * 退回办件列表
     *
     * @param query 查询参数
     * @return 列表
     */
    @RequestMapping(value = "th", method = POST)
    public Result getPrjTh(@RequestBody Query query) {

        query.setNumPerPage(Constant.API_PAGE_SIZE);
        Pager<ProjectInfo> result = projectService.getPrjTh(query);
        if (result.getTotal() > 0) {
            return new Result(Result.SUCC, result);
        }
        return new Result(Result.FAILURE, "暂无数据!");
    }


}
